{% extends "后台管理/template.html" %}

{% block title %}活动管理{% endblock %}

{% block css %}
<style>
    /* 顶部通知样式 */
    .toast-container {
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 9999;
    }
    
    .toast-notification {
        padding: 12px 24px;
        border-radius: 8px;
        margin-bottom: 10px;
        min-width: 300px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        animation: slideIn 0.3s ease;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }
    
    .toast-success {
        background-color: #28a745;
        color: white;
    }
    
    .toast-error {
        background-color: #dc3545;
        color: white;
    }
    
    .toast-warning {
        background-color: #ffc107;
        color: #000;
    }
    
    @keyframes slideIn {
        from {
            transform: translateX(100%);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }
    
    @keyframes fadeOut {
        from {
            opacity: 1;
        }
        to {
            opacity: 0;
        }
    }

    .activity-card {
        transition: all 0.3s ease;
    }
    .activity-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 5px 15px rgba(0,0,0,0.1);
    }
    .cover-image {
        height: 200px;
        object-fit: cover;
        border-radius: 8px;
    }
    .status-badge {
        position: absolute;
        top: 10px;
        right: 10px;
    }

    .toast-notification .btn-close {
        padding: 0.5rem;
        margin: -0.5rem -0.5rem -0.5rem 0.5rem;
        width: 1.5em;
        height: 1.5em;
        opacity: 0.8;
        cursor: pointer;
        background: transparent url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='%23fff'%3e%3cpath d='M.293.293a1 1 0 011.414 0L8 6.586 14.293.293a1 1 0 111.414 1.414L9.414 8l6.293 6.293a1 1 0 01-1.414 1.414L8 9.414l-6.293 6.293a1 1 0 01-1.414-1.414L6.586 8 .293 1.707a1 1 0 010-1.414z'/%3e%3c/svg%3e") center/1em auto no-repeat;
    }

    .toast-notification .btn-close:hover {
        opacity: 1;
    }

    .toast-warning .btn-close {
        background: transparent url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='%23000'%3e%3cpath d='M.293.293a1 1 0 011.414 0L8 6.586 14.293.293a1 1 0 111.414 1.414L9.414 8l6.293 6.293a1 1 0 01-1.414 1.414L8 9.414l-6.293 6.293a1 1 0 01-1.414-1.414L6.586 8 .293 1.707a1 1 0 010-1.414z'/%3e%3c/svg%3e") center/1em auto no-repeat;
    }

    /* 活动详情模态框样式 */
    .modal-body.scrollable-content {
        max-height: calc(100vh - 210px);
        overflow-y: auto;
        overflow-x: hidden;
        padding: 20px;
    }

    /* 自定义滚动条样式 */
    .scrollable-content::-webkit-scrollbar {
        width: 6px;
    }

    .scrollable-content::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 3px;
    }

    .scrollable-content::-webkit-scrollbar-thumb {
        background: #888;
        border-radius: 3px;
    }

    .scrollable-content::-webkit-scrollbar-thumb:hover {
        background: #555;
    }

    /* 图片预览模态框样式 */
    .image-preview-modal {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.9);
        z-index: 9999;
        cursor: zoom-out;
    }

    .image-preview-content {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        max-width: 90%;
        max-height: 90vh;
    }

    .image-preview-content img {
        max-width: 100%;
        max-height: 90vh;
        object-fit: contain;
        border-radius: 8px;
        box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
    }

    /* 添加图片点击提示 */
    [data-preview] {
        cursor: zoom-in;
    }

    /* 添加搜索相关样式 */
    .input-group .btn-primary {
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .input-group .btn-primary i {
        font-size: 1.2rem;
    }

    /* 搜索结果为空时的样式 */
    .text-center.text-muted i {
        opacity: 0.5;
    }

    /* 搜索框悬停和焦点样式 */
    .input-group .form-control:hover,
    .input-group .form-control:focus {
        border-color: #696cff;
        box-shadow: none;
    }

    /* 奖励列表样式优化 */
    .reward-list {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 15px;
        max-height: 60vh;
        overflow-y: auto;
        padding: 15px;
        margin: -15px;
    }

    .reward-item {
        background: #fff;
        border-radius: 12px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        transition: all 0.3s ease;
        border: 1px solid #e9ecef;
        padding: 20px;
        width: 100%;
        min-width: 0;
    }

    .reward-item:hover {
        transform: translateY(-2px);
        box-shadow: 0 5px 15px rgba(0,0,0,0.15);
    }

    .reward-image-container {
        position: relative;
        margin-bottom: 15px;
        display: flex;
        gap: 15px;
        align-items: flex-start;
        flex-wrap: wrap;
    }

    .reward-image-preview {
        width: 120px;
        height: 120px;
        background: #f8f9fa;
        border-radius: 8px;
        overflow: hidden;
        position: relative;
        border: 1px solid #e9ecef;
    }

    .reward-preview {
        width: 100%;
        height: 100%;
        object-fit: cover;
        cursor: pointer;
    }

    .reward-image-actions {
        flex: 1;
        display: flex;
        flex-direction: column;
        min-width: 200px;
    }

    .reward-image-actions input[type="file"] {
        display: none;
    }

    .reward-info {
        padding: 15px 0;
        width: 100%;
    }

    .reward-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
    }

    .reward-name {
        font-size: 1.1em;
        font-weight: 600;
        flex: 1;
        margin-right: 10px;
        padding: 8px 12px;
        border: 1px solid #e9ecef;
        border-radius: 6px;
    }

    .reward-details {
        display: flex;
        flex-direction: column;
        gap: 15px;
        width: 100%;
    }

    .reward-type {
        padding: 8px 12px;
        border: 1px solid #e9ecef;
        border-radius: 6px;
        background-color: #fff;
    }

    .reward-counts {
        display: flex;
        gap: 15px;
        flex-wrap: wrap;
    }

    .quantity-group {
        flex: 1;
        min-width: 120px;
    }

    .quantity-group label {
        display: block;
        font-size: 0.85em;
        color: #666;
        margin-bottom: 8px;
        font-weight: 500;
    }

    .quantity-group input {
        padding: 8px 12px;
        border: 1px solid #e9ecef;
        border-radius: 6px;
        width: 100%;
    }

    .reward-description {
        padding: 8px 12px;
        border: 1px solid #e9ecef;
        border-radius: 6px;
        resize: vertical;
        min-height: 80px;
    }

    /* 剩余数量显示 */
    .remaining-badge {
        position: absolute;
        top: 10px;
        right: 10px;
        background: rgba(0,0,0,0.6);
        color: white;
        padding: 4px 8px;
        border-radius: 4px;
        font-size: 0.85em;
    }

    /* 空状态提示样式 */
    .reward-list .text-muted {
        text-align: center;
        padding: 40px;
        background: #f8f9fa;
        border-radius: 12px;
        border: 2px dashed #dee2e6;
        margin: 20px 0;
        grid-column: 1 / -1;
    }

    .reward-list .text-muted i {
        font-size: 48px;
        display: block;
        margin-bottom: 10px;
        opacity: 0.5;
    }

    /* 调整模态框层级 */
    .modal {
        z-index: 1050;
    }
    
    /* 添加奖励模态框需要更高层级 */
    #addRewardModal {
        z-index: 1060;
    }
    
    /* 添加奖励模态框的背景遮罩也需要更高层级 */
    #addRewardModal + .modal-backdrop {
        /* z-index: 1055; */
    }

    /* 添加多层模态框支持的样式 */
    .modal-stacked {
        overflow-y: hidden !important;
    }

    .modal-stacked .modal-backdrop {
        opacity: 0.1 !important;
    }

    /* 确保添加奖励模态框在编辑活动模态框之上 */
    .modal-backdrop {
        z-index: 1040;
    }

    .modal-stacked + .modal-backdrop + .modal {
        /* z-index: 1060; */
    }

    .modal-stacked + .modal-backdrop + .modal + .modal-backdrop {
        /* z-index: 1055; */
    }

    /* 确保模态框内容的层级正确 */
    .modal-dialog {
        z-index: 1052;
    }

    .modal-backdrop {
        /* z-index: 1051; */
    }

    .reward-item {
        position: relative;
        z-index: 1;
    }

    .reward-item .card-body {
        position: relative;
        z-index: 2;
    }

    /* 删除按钮样式优化 */
    .reward-item .btn-outline-danger {
        padding: 6px 12px;
        font-size: 0.9em;
        border-radius: 6px;
        transition: all 0.2s ease;
    }

    /* 上传图片按钮样式优化 */
    .reward-image-actions .btn-outline-primary {
        padding: 8px 15px;
        font-size: 0.9em;
        border-radius: 6px;
        width: fit-content;
        display: flex;
        align-items: center;
        gap: 5px;
    }

    /* 滚动条样式优化 */
    .reward-list::-webkit-scrollbar {
        width: 6px;
    }

    .reward-list::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 3px;
    }

    .reward-list::-webkit-scrollbar-thumb {
        background: #ccc;
        border-radius: 3px;
    }

    .reward-list::-webkit-scrollbar-thumb:hover {
        background: #aaa;
    }

    /* 响应式布局调整 */
    @media (max-width: 1200px) {
        .reward-list {
            grid-template-columns: 1fr;
        }
    }

    /* 修改编辑活动模态框的样式 */
    #editActivityModal .modal-dialog {
        max-width: 80vw;
    }

    #editActivityModal .modal-body {
        max-height: 85vh;
        overflow-y: auto;
    }
</style>
{% endblock %}

{% block content %}
<div class="toast-container" id="toastContainer"></div>

<div class="container-xxl flex-grow-1 container-p-y">
    <!-- 页面标题 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h4 class="fw-bold py-3 mb-4">活动管理</h4>
        <div class="d-flex align-items-center gap-3">
            <!-- 搜索框 -->
            <div class="input-group" style="width: 300px;">
                <input type="text" 
                       class="form-control" 
                       placeholder="搜索活动..." 
                       id="searchInput"
                       @keyup.enter="handleSearch">
                <button class="btn btn-primary" 
                        type="button" 
                        onclick="handleSearch()">
                    <i class="bx bx-search"></i>
                </button>
            </div>
            <!-- 创建活动按钮 -->
            <button type="button" 
                    class="btn btn-primary" 
                    data-bs-toggle="modal" 
                    data-bs-target="#createActivityModal">
                <i class="bx bx-plus me-1"></i> 创建活动
            </button>
        </div>
    </div>

    <!-- 筛选栏 -->
    <div class="card mb-4">
        <div class="card-body">
            <div class="row g-3">
                <div class="col-md-3">
                    <select class="form-select" id="statusFilter" onchange="handleSearch()">
                        <option value="">所有状态</option>
                        <option value="draft">草稿</option>
                        <option value="published">已发布</option>
                        <option value="ended">已结束</option>
                    </select>
                </div>
            </div>
        </div>
    </div>

    <!-- 活动列表 -->
    <div class="row g-4" id="activityList">
        <!-- 活动卡片将通过 JS 动态加载 -->
    </div>

    <!-- 分页控件 -->
    <div class="d-flex justify-content-between align-items-center mt-4">
        <div class="text-muted">
            总计: <span id="totalCount">0</span> 个活动
        </div>
        <nav aria-label="Page navigation">
            <ul class="pagination" id="pagination"></ul>
        </nav>
    </div>
</div>

<!-- 创建活动模态框 -->
<div class="modal fade" id="createActivityModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">创建活动</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="createActivityForm">
                    <!-- 活动基本信息 -->
                    <div class="mb-3">
                        <label class="form-label">活动标题</label>
                        <input type="text" class="form-control" id="createTitle" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">活动描述</label>
                        <textarea class="form-control" id="createDescription" rows="3" required></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">活动封面</label>
                        <input type="file" class="form-control" id="createCoverImage" accept="image/*">
                        <img id="createCoverPreview" src="" class="mt-2" style="max-width: 100%; display: none;">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">活动状态</label>
                        <select class="form-select" id="createStatus" required>
                            <option value="draft">草稿</option>
                            <option value="published">已发布</option>
                            <option value="ended">已结束</option>
                        </select>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="submitCreateActivity()">创建活动</button>
            </div>
        </div>
    </div>
</div>

<!-- 添加奖励模态框 -->
<div class="modal fade" 
     id="addRewardModal" 
     tabindex="-1" 
     data-bs-backdrop="static"
     aria-modal="true"
     role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">添加奖励</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="addRewardForm">
                    <div class="mb-3">
                        <label class="form-label">奖励名称</label>
                        <input type="text" class="form-control" id="newRewardName" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">奖励类型</label>
                        <select class="form-select" id="newRewardType" required>
                            <option value="physical">实物</option>
                            <option value="points">积分</option>
                            <option value="coupon">优惠券</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">奖励数量</label>
                        <input type="number" class="form-control" id="newRewardQuantity" min="1" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">剩余数量</label>
                        <input type="number" class="form-control" id="newRewardRemaining" min="0" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">奖励描述</label>
                        <textarea class="form-control" id="newRewardDescription" rows="2"></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">奖励图片</label>
                        <input type="file" class="form-control" id="newRewardImage" accept="image/*">
                        <img id="newRewardPreview" src="" class="mt-2" style="max-width: 100%; display: none;">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="submitNewReward()">添加</button>
            </div>
        </div>
    </div>
</div>

<!-- 活动详情模态框 -->
<div class="modal fade" id="activityDetailModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">活动详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body scrollable-content" id="activityDetailContent">
                <!-- 详情内容将通过 JS 动态加载 -->
            </div>
        </div>
    </div>
</div>

<!-- 添加图片预览模态框 -->
<div class="image-preview-modal" id="imagePreviewModal" onclick="closeImagePreview()">
    <div class="image-preview-content">
        <img id="previewImage" src="" alt="图片预览">
    </div>
</div>

<!-- 编辑活动模态框 -->
<div class="modal fade" id="editActivityModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">编辑活动</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="editActivityForm">
                    <input type="hidden" id="editActivityId">
                    <!-- 活动基本信息 -->
                    <h6 class="mb-3">活动基本信息</h6>
                    <div class="mb-3">
                        <label class="form-label">活动标题</label>
                        <input type="text" class="form-control" id="editTitle" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">活动描述</label>
                        <textarea class="form-control" id="editDescription" rows="3" required></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">活动封面</label>
                        <input type="file" class="form-control" id="editCoverImage" accept="image/*">
                        <img id="editCoverPreview" src="" alt="封面预览" class="mt-2" style="max-width: 200px; display: none;">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">活动状态</label>
                        <select class="form-select" id="editStatus" required>
                            <option value="draft">草稿</option>
                            <option value="published">已发布</option>
                            <option value="ended">已结束</option>
                        </select>
                    </div>
                    <!-- 奖励列表 -->
                    <h6 class="mb-3 mt-4">奖励列表</h6>
                    <div class="mb-3">
                        <div class="d-flex justify-content-end mb-3">
                            <button type="button" class="btn btn-primary btn-sm" onclick="showAddRewardModal()">
                                <i class="bx bx-plus"></i> 添加奖励
                            </button>
                        </div>
                        <div id="editRewardsList" class="reward-list">
                            <!-- 奖励项会动态添加到这里 -->
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="submitEditActivity()">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 添加奖励项模板 -->
<template id="rewardItemTemplate">
    <div class="reward-item">
        <div class="card-body">
            <!-- 删除按钮 -->
            <div class="d-flex justify-content-end mb-2">
                <button type="button" class="btn btn-sm btn-outline-danger" onclick="deleteReward(this)">
                    <i class="bx bx-trash"></i> 删除奖励
                </button>
            </div>
            <!-- 奖励图片 -->
            <div class="reward-image-container">
                <div class="reward-image-preview">
                    <img class="reward-preview" src="" style="display: none;">
                </div>
                <div class="reward-image-actions">
                    <input type="file" class="form-control reward-image" accept="image/*">
                    <button type="button" class="btn btn-sm btn-outline-primary mt-2" onclick="triggerImageUpload(this)">
                        <i class="bx bx-upload"></i> 上传图片
                    </button>
                </div>
            </div>
            
            <!-- 奖励信息 -->
            <div class="reward-info">
                <input type="hidden" class="reward-id">
                <div class="reward-header">
                    <input type="text" class="form-control reward-name" placeholder="奖励名称" required>
                </div>
                
                <div class="reward-details">
                    <div class="form-group">
                        <select class="form-select reward-type" required>
                            <option value="physical">实物</option>
                            <option value="points">积分</option>
                            <option value="coupon">优惠券</option>
                        </select>
                    </div>
                    
                    <div class="reward-counts">
                        <div class="quantity-group">
                            <label>数量</label>
                            <input type="number" class="form-control reward-quantity" min="1" required>
                        </div>
                        <div class="quantity-group">
                            <label>剩余</label>
                            <input type="number" class="form-control reward-remaining" min="0" required>
                        </div>
                    </div>
                    
                    <textarea class="form-control reward-description" 
                              rows="2" 
                              placeholder="奖励描述"></textarea>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
let currentPage = 1;
const pageSize = 10;

// 加载活动列表
async function loadActivities(page = 1) {
    try {
        const status = document.getElementById('statusFilter').value;
        const response = await fetch(`/api/activity/list/?page=${page}&page_size=${pageSize}&status=${status}`);
        const data = await response.json();
        
        if (data.code === 200) {
            renderActivities(data.data);
            renderPagination(data.data.total);
        }
    } catch (error) {
        console.error('加载活动列表失败:', error);
        showToast('加载活动列表失败', 'error');
    }
}

// 渲染活动列表
function renderActivities(data) {
    const activityList = document.getElementById('activityList');
    activityList.innerHTML = data.list.map(activity => `
        <div class="col-md-4">
            <div class="card activity-card h-100">
                <img src="${activity.cover_image}" 
                     class="card-img-top cover-image" 
                     alt="${activity.title}" 
                     onclick="showImagePreview('${activity.cover_image}')"
                     style="cursor: pointer;">
                <div class="status-badge">
                    <span class="badge bg-${getStatusBadgeClass(activity.status)}">${getStatusText(activity.status)}</span>
                </div>
                <div class="card-body">
                    <h5 class="card-title">${activity.title}</h5>
                    <p class="card-text text-truncate">${activity.description}</p>
                    <button class="btn btn-primary btn-sm" onclick="viewActivityDetail(${activity.id})">
                        查看详情
                    </button>
                </div>
            </div>
        </div>
    `).join('');
    
    document.getElementById('totalCount').textContent = data.total;
}

// 初始化封面图片预览
function initCoverImagePreview() {
    // 创建活动的封面预览
    document.getElementById('createCoverImage')?.addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            // 检查文件大小
            if (file.size > 2 * 1024 * 1024) {
                showToast('图片大小不能超过2MB', 'error');
                this.value = '';
                return;
            }
            
            // 检查文件类型
            if (!file.type.startsWith('image/')) {
                showToast('请选择图片文件', 'error');
                this.value = '';
                return;
            }
            
            const reader = new FileReader();
            reader.onload = function(e) {
                const preview = document.getElementById('createCoverPreview');
                preview.src = e.target.result;
                preview.style.display = 'block';
            };
            reader.readAsDataURL(file);
        }
    });
    
    // 编辑活动的封面预览
    document.getElementById('editCoverImage')?.addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            // 检查文件大小
            if (file.size > 2 * 1024 * 1024) {
                showToast('图片大小不能超过2MB', 'error');
                this.value = '';
                return;
            }
            
            // 检查文件类型
            if (!file.type.startsWith('image/')) {
                showToast('请选择图片文件', 'error');
                this.value = '';
                return;
            }
            
            const reader = new FileReader();
            reader.onload = function(e) {
                const preview = document.getElementById('editCoverPreview');
                preview.src = e.target.result;
                preview.style.display = 'block';
            };
            reader.readAsDataURL(file);
        }
    });
}

// 移除封面图片
function removeCoverImage() {
    const input = document.querySelector('input[name="cover_image"]');
    const preview = document.getElementById('coverPreview');
    input.value = '';
    preview.src = '';
    preview.parentElement.style.display = 'none';
}

// 重置表单时清除预览
document.getElementById('createActivityForm').addEventListener('reset', function() {
    const preview = document.getElementById('coverPreview');
    preview.src = '';
    preview.parentElement.style.display = 'none';
});

// 修改添加奖励函数
async function addReward(mode) {
    try {
        // 获取活动ID
        const activityId = document.getElementById('editActivityId').value;
        
        // 准备表单数据
        const formData = new FormData();
        formData.append('activity_id', activityId);
        formData.append('reward_name', '新奖励'); // 默认名称
        formData.append('reward_type', 'points'); // 默认类型
        formData.append('quantity', '1'); // 默认数量
        formData.append('remaining', '1'); // 默认剩余
        
        // 创建新奖励
        const response = await fetch('/api/reward/create/', {
            method: 'POST',
            body: formData
        });
        
        const data = await response.json();
        
        if (data.code === 200) {
            // 创建成功后，刷新奖励列表
            const rewardsResponse = await fetch(`/api/reward/list/${activityId}/`);
            const rewardsData = await rewardsResponse.json();
            
            if (rewardsData.code === 200) {
                const rewardsList = document.getElementById('editRewardsList');
                rewardsList.innerHTML = '';
                
                if (rewardsData.data && rewardsData.data.length > 0) {
                    rewardsData.data.forEach(reward => {
                        renderRewardItem(reward, rewardsList);
                    });
                } else {
                    showEmptyRewardsList(rewardsList);
                }
            }
            
            showToast('奖励添加成功', 'success');
        } else {
            throw new Error(data.message || '添加奖励失败');
        }
    } catch (error) {
        console.error('添加奖励失败:', error);
        showToast('添加奖励失败: ' + error.message, 'error');
    }
}

// 渲染奖励项
function renderRewardItem(reward, container) {
    if (!reward || !container) return;
    
    const template = document.getElementById('rewardItemTemplate');
    if (!template) {
        console.error('找不到奖励项模板');
        return;
    }
    
    const tempDiv = document.createElement('div');
    tempDiv.innerHTML = template.innerHTML;
    const rewardItem = tempDiv.firstElementChild;
    
    try {
        // 填充奖励数据
        rewardItem.querySelector('.reward-id').value = reward.id;
        rewardItem.querySelector('.reward-name').value = reward.reward_name;
        rewardItem.querySelector('.reward-type').value = reward.reward_type;
        rewardItem.querySelector('.reward-quantity').value = reward.quantity;
        rewardItem.querySelector('.reward-remaining').value = reward.remaining;
        rewardItem.querySelector('.reward-description').value = reward.description || '';
        
        if (reward.image) {
            const previewImg = rewardItem.querySelector('.reward-preview');
            if (previewImg) {
                previewImg.src = reward.image;
                previewImg.style.display = 'block';
                previewImg.onclick = () => showImagePreview(reward.image);
            }
        }
        
        // 初始化图片上传预览
        initRewardImagePreview(rewardItem);
        
        container.appendChild(rewardItem);
    } catch (error) {
        console.error('渲染奖励项时出错:', error);
    }
}

// 显示空奖励列表提示
function showEmptyRewardsList(container) {
    container.innerHTML = `
        <div class="text-center text-muted py-3">
            <i class="bx bx-info-circle mb-2" style="font-size: 24px;"></i>
            <p class="mb-0">暂无奖励，点击上方按钮添加奖励</p>
        </div>
    `;
}

// 移除奖励表单
function removeReward(button) {
    const rewardItem = button.closest('.reward-item');
    const rewardsList = document.getElementById('editRewardsList');
    rewardItem.remove();
    
    // 如果没有奖励了，显示提示信息
    if (rewardsList.children.length === 0) {
        rewardsList.innerHTML = `
            <div class="text-center text-muted py-3">
                <i class="bx bx-info-circle mb-2" style="font-size: 24px;"></i>
                <p class="mb-0">暂无奖励，点击上方按钮添加奖励</p>
            </div>
        `;
    }
}

// 修改初始化奖励图片预览函数
function initRewardImagePreview(rewardItem) {
    if (!rewardItem) return;
    
    const imageInput = rewardItem.querySelector('.reward-image');
    if (!imageInput) return;
    const previewImg = rewardItem.querySelector('.reward-preview');
    if (!previewImg) return;
    
    imageInput.addEventListener('change', function(event) {
        const file = event.target.files[0];
        if (file) {
            if (file.size > 2 * 1024 * 1024) {
                showToast('图片大小不能超过2MB', 'error');
                this.value = '';
                return;
            }
            
            const reader = new FileReader();
            reader.onload = function(e) {
                previewImg.src = e.target.result;
                previewImg.style.display = 'block';
                previewImg.onclick = () => showImagePreview(e.target.result);
            };
            reader.readAsDataURL(file);
        }
    });
}

// 移除奖励图片
function removeRewardImage(button) {
    const previewContainer = button.closest('.reward-preview');
    const input = previewContainer.nextElementSibling;
    input.value = '';
    previewContainer.querySelector('img').src = '';
    previewContainer.style.display = 'none';
}

// 修改创建活动的函数
async function submitCreateActivity() {
    try {
        const formData = new FormData();
        
        // 添加活动基本信息
        formData.append('title', document.getElementById('createTitle').value);
        formData.append('description', document.getElementById('createDescription').value);
        formData.append('status', document.getElementById('createStatus').value);
        formData.append('user_id', '7784c3d2-8d40-4211-99e9-2158b9c4b40c');
        
        const coverImage = document.getElementById('createCoverImage').files[0];
        if (coverImage) {
            formData.append('cover_image', coverImage);
        }
        
        // 提交创建活动请求
        const response = await fetch('/api/activity/create/', {
            method: 'POST',
            body: formData
        });
        
        const data = await response.json();
        
        if (data.code === 200) {
            showToast('活动创建成功', 'success');
            bootstrap.Modal.getInstance(document.getElementById('createActivityModal')).hide();
            
            // 创建成功后，直接打开编辑模态框以添加奖励
            setTimeout(() => {
                editActivity(data.data.id);
            }, 500);
            
            handleSearch(currentPage); // 刷新列表
        } else {
            throw new Error(data.message || '创建活动失败');
        }
    } catch (error) {
        console.error('创建活动失败:', error);
        showToast('创建活动失败: ' + error.message, 'error');
    }
}

// 表单验证
function validateForm(form) {
    // 验证活动基本信息
    if (!form.checkValidity()) {
        showToast('请填写所有必填项', 'error');
        return false;
    }
    
    // 验证至少有一个奖励
    const rewardItems = form.querySelectorAll('.reward-item');
    if (rewardItems.length === 0) {
        showToast('请至少添加一个奖励', 'error');
        return false;
    }
    
    // 验证每个奖励的必填项
    for (let i = 0; i < rewardItems.length; i++) {
        const item = rewardItems[i];
        const requiredInputs = item.querySelectorAll('[required]');
        for (const input of requiredInputs) {
            if (!input.value) {
                showToast(`请完善奖励 #${i + 1} 的所有必填项`, 'error');
                return false;
            }
        }
    }
    
    return true;
}

// 清除所有预览
function clearAllPreviews() {
    document.getElementById('coverPreview').src = '';
    document.getElementById('coverPreview').parentElement.style.display = 'none';
    
    document.querySelectorAll('.reward-preview').forEach(preview => {
        preview.querySelector('img').src = '';
        preview.style.display = 'none';
    });
}

// 查看活动详情
async function viewActivityDetail(activityId) {
    try {
        // 并行请求活动详情和奖励列表
        const [activityResponse, rewardsResponse] = await Promise.all([
            fetch(`/api/activity/detail/?activity_id=${activityId}`),
            fetch(`/api/reward/list/${activityId}/`)
        ]);

        const [activityData, rewardsData] = await Promise.all([
            activityResponse.json(),
            rewardsResponse.json()
        ]);

        if (activityData.code === 200 && rewardsData.code === 200) {
            const activity = activityData.data;
            const rewards = rewardsData.data;

            document.getElementById('activityDetailContent').innerHTML = `
                <div class="text-center mb-4">
                    <img src="${activity.cover_image}" class="img-fluid rounded" style="max-height: 300px;" data-preview>
                </div>
                <div class="mb-3">
                    <h4>${activity.title}</h4>
                    <span class="badge bg-${getStatusBadgeClass(activity.status)}">${getStatusText(activity.status)}</span>
                </div>
                <div class="mb-3">
                    <h6>活动描述</h6>
                    <p>${activity.description}</p>
                </div>
                <div class="row mb-4">
                    <div class="col-md-6">
                        <p><strong>创建时间：</strong>${activity.created_at}</p>
                    </div>
                    <div class="col-md-6">
                        <p><strong>更新时间：</strong>${activity.updated_at}</p>
                    </div>
                </div>

                <!-- 奖励信息 -->
                <div class="rewards-section">
                    <h5 class="mb-3">活动奖励</h5>
                    <div class="row g-3">
                        ${rewards.map(reward => `
                            <div class="col-md-6">
                                <div class="card h-100">
                                    <div class="row g-0">
                                        <div class="col-md-4">
                                            <img src="${reward.image}" class="img-fluid rounded-start h-100" 
                                                 style="object-fit: cover;" alt="${reward.reward_name}" 
                                                 data-preview>
                                        </div>
                                        <div class="col-md-8">
                                            <div class="card-body">
                                                <h6 class="card-title">${reward.reward_name}</h6>
                                                <p class="card-text">
                                                    <small class="text-muted">
                                                        ${getRewardTypeText(reward.reward_type)}
                                                    </small>
                                                </p>
                                                <p class="card-text">
                                                    ${reward.description || '暂无描述'}
                                                </p>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <span class="badge bg-primary">
                                                        剩余: ${reward.remaining}/${reward.quantity}
                                                    </span>
                                                    ${getRewardStatusBadge(reward.remaining, reward.quantity)}
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        `).join('')}
                    </div>
                    ${rewards.length === 0 ? '<div class="text-center text-muted">暂无奖励信息</div>' : ''}
                </div>
            `;
            $('#activityDetailModal').modal('show');
        }
    } catch (error) {
        console.error('获取活动详情失败:', error);
        showToast('获取活动详情失败', 'error');
    }
}

// 获取奖励类型文本
function getRewardTypeText(type) {
    const typeMap = {
        'points': '积分奖励',
        'virtual': '虚拟物品',
        'physical': '实物奖励'
    };
    return typeMap[type] || type;
}

// 获取奖励状态徽章
function getRewardStatusBadge(remaining, total) {
    const percentage = (remaining / total) * 100;
    if (remaining === 0) {
        return '<span class="badge bg-danger">已领完</span>';
    } else if (percentage <= 20) {
        return '<span class="badge bg-warning">即将领完</span>';
    } else {
        return '<span class="badge bg-success">领取中</span>';
    }
}

// 工具函数
function getStatusBadgeClass(status) {
    const statusMap = {
        'draft': 'warning',
        'published': 'success',
        'ended': 'secondary'
    };
    return statusMap[status] || 'primary';
}

function getStatusText(status) {
    const statusMap = {
        'draft': '草稿',
        'published': '已发布',
        'ended': '已结束'
    };
    return statusMap[status] || status;
}

// 显示通知的函数
function showToast(message, type = 'success') {
    const container = document.getElementById('toastContainer');
    const toast = document.createElement('div');
    toast.className = `toast-notification toast-${type}`;
    
    // 创建关闭按钮
    const closeBtn = document.createElement('button');
    closeBtn.className = 'btn-close';
    closeBtn.setAttribute('aria-label', 'Close');
    closeBtn.onclick = () => {
        toast.style.animation = 'fadeOut 0.3s ease forwards';
        setTimeout(() => toast.remove(), 300);
    };
    
    // 添加图标
    let icon = '';
    switch(type) {
        case 'success':
            icon = '<i class="bx bx-check-circle me-2"></i>';
            break;
        case 'error':
            icon = '<i class="bx bx-x-circle me-2"></i>';
            break;
        case 'warning':
            icon = '<i class="bx bx-error-circle me-2"></i>';
            break;
    }
    
    toast.innerHTML = `
        <div class="d-flex align-items-center">
            ${icon}
            <span>${message}</span>
        </div>
    `;
    toast.appendChild(closeBtn);
    
    container.appendChild(toast);
    
    // 3秒后自动移除
    setTimeout(() => {
        if (toast && toast.parentElement) {
            toast.style.animation = 'fadeOut 0.3s ease forwards';
            setTimeout(() => toast.remove(), 300);
        }
    }, 3000);
}

// 渲染分页
function renderPagination(total) {
    const totalPages = Math.ceil(total / pageSize);
    const pagination = document.getElementById('pagination');
    
    let html = '';
    for (let i = 1; i <= totalPages; i++) {
        html += `
            <li class="page-item ${i === currentPage ? 'active' : ''}">
                <a class="page-link" href="javascript:void(0)" onclick="changePage(${i})">${i}</a>
            </li>
        `;
    }
    pagination.innerHTML = html;
}

function changePage(page) {
    handleSearch(page);
}

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', () => {
    handleSearch(1);
    initCoverImagePreview();
});

// 图片预览相关函数
function showImagePreview(imgSrc) {
    const modal = document.getElementById('imagePreviewModal');
    const previewImg = document.getElementById('previewImage');
    
    // 设置预览图片
    previewImg.src = imgSrc;
    
    // 显示模态框
    modal.style.display = 'block';
    
    // 阻止事件冒泡
    event?.stopPropagation();
}

function closeImagePreview() {
    const modal = document.getElementById('imagePreviewModal');
    modal.style.display = 'none';
}

// 初始化所有可预览图片
function initializeImagePreviews() {
    // 为所有带有 data-preview 属性的图片添加点击事件
    document.querySelectorAll('[data-preview]').forEach(img => {
        img.addEventListener('click', () => showImagePreview(img.src));
    });
}

// 搜索活动
async function handleSearch(page = 1) {
    try {
        const searchInput = document.querySelector('.input-group input');
        const keyword = searchInput ? searchInput.value.trim() : '';
        const status = document.getElementById('statusFilter').value;
        currentPage = page;
        
        // 构建查询参数
        const params = new URLSearchParams({
            page: currentPage,
            page_size: pageSize
        });
        
        if (keyword) {
            params.append('keyword', keyword);
        }
        if (status) {
            params.append('status', status);
        }

        const response = await fetch(`/api/activity/search/?${params.toString()}`);
        const data = await response.json();

        if (data.code === 200) {
            // 更新活动列表
            const container = document.getElementById('activityList');
            
            if (!data.data.list || data.data.list.length === 0) {
                container.innerHTML = `
                    <div class="col-12 text-center text-muted my-5">
                        <i class="bx bx-search-alt" style="font-size: 48px;"></i>
                        <p class="mt-2">未找到相关活动</p>
                    </div>
                `;
                document.getElementById('totalCount').textContent = '0';
                document.getElementById('pagination').innerHTML = '';
                return;
            }

            container.innerHTML = data.data.list.map(activity => `
                <div class="col-md-6 col-lg-4">
                    <div class="card h-100">
                        <img class="card-img-top" 
                             src="${activity.cover_image || '/static/default/activity.png'}" 
                             alt="${activity.title}"
                             style="height: 200px; object-fit: cover;"
                             onerror="this.src='/static/default/activity.png'">
                        <div class="card-body">
                            <h5 class="card-title">${activity.title}</h5>
                            <p class="card-text text-truncate">${activity.description}</p>
                            <div class="d-flex justify-content-between align-items-center">
                                <span class="badge bg-${getStatusBadgeClass(activity.status)}">
                                    ${getStatusText(activity.status)}
                                </span>
                                <div class="btn-group">
                                    <button type="button" 
                                            class="btn btn-sm btn-outline-primary"
                                            onclick="viewActivityDetail(${activity.id})">
                                        查看
                                    </button>
                                    <button type="button" 
                                            class="btn btn-sm btn-outline-secondary"
                                            onclick="editActivity(${activity.id})">
                                        编辑
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            `).join('');

            // 更新总数和分页
            document.getElementById('totalCount').textContent = data.data.total;
            renderPagination(data.data.total);
        } else {
            showToast(data.message || '搜索失败', 'error');
        }
    } catch (error) {
        console.error('搜索失败:', error);
        showToast('搜索失败', 'error');
    }
}

// 监听搜索框的回车事件
document.getElementById('searchInput').addEventListener('keyup', function(event) {
    if (event.key === 'Enter') {
        handleSearch(1);
    }
});

// 修改分页切换函数
function changePage(page) {
    handleSearch(page);
}

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', () => {
    handleSearch(1);
});

// 编辑活动
async function editActivity(activityId) {
    try {
        // 获取活动详情
        const response = await fetch(`/api/activity/detail/?activity_id=${activityId}`);
        const data = await response.json();
        
        if (data.code === 200) {
            const activity = data.data;
            
            // 填充活动基本信息
            document.getElementById('editActivityId').value = activity.id;
            document.getElementById('editTitle').value = activity.title;
            document.getElementById('editDescription').value = activity.description;
            document.getElementById('editStatus').value = activity.status;
            
            if (activity.cover_image) {
                document.getElementById('editCoverPreview').src = activity.cover_image;
                document.getElementById('editCoverPreview').style.display = 'block';
            } else {
                document.getElementById('editCoverPreview').style.display = 'none';
            }
            
            // 获取并填充奖励信息
            const rewardsResponse = await fetch(`/api/reward/list/${activity.id}/`);
            const rewardsData = await rewardsResponse.json();
            
            console.log('获取到的奖励数据:', rewardsData); // 添加调试日志
            
            if (rewardsData.code === 200) {
                const rewardsList = document.getElementById('editRewardsList');
                rewardsList.innerHTML = '';
                
                if (!rewardsData.data || rewardsData.data.length === 0) {
                    showEmptyRewardsList(rewardsList);
                } else {
                    rewardsData.data.forEach(reward => {
                        renderRewardItem(reward, rewardsList);
                    });
                }
            }
            
            // 显示模态框
            const modal = new bootstrap.Modal(document.getElementById('editActivityModal'));
            modal.show();
        } else {
            showToast(data.message || '获取活动详情失败', 'error');
        }
    } catch (error) {
        console.error('编辑活动失败:', error);
        showToast('编辑活动失败', 'error');
    }
}

// 提交编辑活动
async function submitEditActivity() {
    try {
        const activityId = document.getElementById('editActivityId').value;
        const formData = new FormData();
        
        // 添加活动基本信息
        formData.append('activity_id', activityId);
        formData.append('title', document.getElementById('editTitle').value);
        formData.append('description', document.getElementById('editDescription').value);
        formData.append('status', document.getElementById('editStatus').value);
        formData.append('user_id', '7784c3d2-8d40-4211-99e9-2158b9c4b40c'); // 添加用户ID
        
        const coverImage = document.getElementById('editCoverImage').files[0];
        if (coverImage) {
            formData.append('cover_image', coverImage);
        }
        
        // 提交活动编辑
        const response = await fetch('/api/activity/edit/', {
            method: 'POST',
            body: formData
        });
        
        const data = await response.json();
        
        if (data.code === 200) {
            // 处理奖励编辑
            const rewardItems = document.getElementById('editRewardsList').querySelectorAll('.reward-item');
            
            for (const item of rewardItems) {
                const rewardFormData = new FormData();
                rewardFormData.append('activity_id', activityId);
                rewardFormData.append('reward_id', item.querySelector('.reward-id').value || '');
                rewardFormData.append('reward_name', item.querySelector('.reward-name').value);
                rewardFormData.append('reward_type', item.querySelector('.reward-type').value);
                rewardFormData.append('quantity', item.querySelector('.reward-quantity').value);
                rewardFormData.append('remaining', item.querySelector('.reward-remaining').value);
                rewardFormData.append('description', item.querySelector('.reward-description').value || '');
                
                const rewardImage = item.querySelector('.reward-image').files[0];
                if (rewardImage) {
                    rewardFormData.append('image', rewardImage);
                }
                
                try {
                    // 提交奖励编辑
                    const rewardResponse = await fetch('/api/reward/edit/', {
                        method: 'POST',
                        body: rewardFormData
                    });
                    const rewardData = await rewardResponse.json();
                    console.log('奖励编辑响应:', rewardData); // 添加调试日志
                    if (rewardData.code !== 200) {
                        throw new Error(rewardData.message || '奖励编辑失败');
                    }
                } catch (error) {
                    console.error('奖励编辑失败:', error);
                    throw new Error(`奖励 "${item.querySelector('.reward-name').value}" 编辑失败: ${error.message}`);
                }
            }
            
            showToast('活动编辑成功', 'success');
            bootstrap.Modal.getInstance(document.getElementById('editActivityModal')).hide();
            handleSearch(currentPage); // 刷新列表
        } else {
            console.error('活动编辑失败:', data);
            showToast(data.message || '活动编辑失败', 'error');
        }
    } catch (error) {
        console.error('提交编辑失败:', error);
        showToast('提交编辑失败: ' + error.message, 'error');
    }
}

// 监听奖励图片上传
document.addEventListener('change', function(event) {
    if (event.target.classList.contains('reward-image')) {
        const file = event.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function(e) {
                const preview = event.target.nextElementSibling;
                preview.src = e.target.result;
                preview.style.display = 'block';
            };
            reader.readAsDataURL(file);
        }
    }
}, true);

// 添加删除奖励的函数
async function deleteReward(button) {
    try {
        const rewardItem = button.closest('.reward-item');
        const rewardId = rewardItem.querySelector('.reward-id').value;
        const rewardName = rewardItem.querySelector('.reward-name').value;
        
        if (!confirm(`确定要删除奖励 "${rewardName}" 吗？`)) {
            return;
        }
        
        if (rewardId) {
            // 如果有 ID，说明是已存在的奖励，需要调用删除 API
            const response = await fetch('/api/reward/edit/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `reward_id=${rewardId}&is_delete=true`
            });
            
            const data = await response.json();
            if (data.code !== 200) {
                throw new Error(data.message || '删除奖励失败');
            }
        }
        
        // 从 DOM 中移除奖励项
        rewardItem.remove();
        
        // 检查是否还有其他奖励
        const rewardsList = document.getElementById('editRewardsList');
        if (rewardsList.children.length === 0) {
            rewardsList.innerHTML = `
                <div class="text-center text-muted py-3">
                    <i class="bx bx-info-circle mb-2" style="font-size: 24px;"></i>
                    <p class="mb-0">暂无奖励，点击上方按钮添加奖励</p>
                </div>
            `;
        }
        
        showToast('奖励删除成功', 'success');
    } catch (error) {
        console.error('删除奖励失败:', error);
        showToast('删除奖励失败: ' + error.message, 'error');
    }
}

// 显示添加奖励模态框
function showAddRewardModal() {
    // 获取编辑活动模态框的实例
    const editModal = document.getElementById('editActivityModal');
    
    // 添加特殊类以处理多层模态框
    editModal.classList.add('modal-stacked');
    
    // 重置表单
    document.getElementById('addRewardForm').reset();
    document.getElementById('newRewardPreview').style.display = 'none';
    
    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('addRewardModal'));
    modal.show();
}

// 提交新奖励
async function submitNewReward() {
    try {
        const activityId = document.getElementById('editActivityId').value;
        const formData = new FormData();
        
        // 添加奖励信息
        formData.append('activity', activityId);
        formData.append('reward_name', document.getElementById('newRewardName').value);
        formData.append('reward_type', document.getElementById('newRewardType').value);
        formData.append('quantity', document.getElementById('newRewardQuantity').value);
        formData.append('remaining', document.getElementById('newRewardRemaining').value);
        formData.append('description', document.getElementById('newRewardDescription').value);
        
        const rewardImage = document.getElementById('newRewardImage').files[0];
        if (rewardImage) {
            formData.append('image', rewardImage);
        }
        
        // 提交创建奖励请求
        const response = await fetch('/api/reward/create/', {
            method: 'POST',
            body: formData
        });
        
        const data = await response.json();
        
        if (data.code === 200) {
            // 关闭模态框
            bootstrap.Modal.getInstance(document.getElementById('addRewardModal')).hide();
            
            // 刷新奖励列表
            const rewardsResponse = await fetch(`/api/reward/list/${activityId}/`);
            const rewardsData = await rewardsResponse.json();
            
            if (rewardsData.code === 200) {
                const rewardsList = document.getElementById('editRewardsList');
                rewardsList.innerHTML = '';
                
                if (rewardsData.data && rewardsData.data.length > 0) {
                    rewardsData.data.forEach(reward => {
                        renderRewardItem(reward, rewardsList);
                    });
                } else {
                    showEmptyRewardsList(rewardsList);
                }
            }
            
            showToast('奖励添加成功', 'success');
        } else {
            throw new Error(data.message || '添加奖励失败');
        }
    } catch (error) {
        console.error('添加奖励失败:', error);
        showToast('添加奖励失败: ' + error.message, 'error');
    }
}

// 监听新奖励图片上传
document.getElementById('newRewardImage')?.addEventListener('change', function(event) {
    const file = event.target.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            const preview = document.getElementById('newRewardPreview');
            preview.src = e.target.result;
            preview.style.display = 'block';
        };
        reader.readAsDataURL(file);
    }
});

// 添加关闭添加奖励模态框的处理
document.getElementById('addRewardModal').addEventListener('hidden.bs.modal', function () {
    // 移除编辑活动模态框的特殊类
    document.getElementById('editActivityModal').classList.remove('modal-stacked');
});

// 添加触发图片上传的函数
function triggerImageUpload(button) {
    const fileInput = button.closest('.reward-image-actions').querySelector('.reward-image');
    fileInput.click();
}
</script>
{% endblock %}


{% block nav_left %}
{% include '后台管理/components/左侧导航栏.html' %}
{% endblock %}


{% block NavBar %}
{% endblock %}

{% block footer %}{% include '后台管理/components/Footer.html' %}{% endblock %}

